<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="注意：只允许选择三级选项"
        :closable="false"
        type="warning"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cap_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="catalist"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="btnDisabled"
            type="primary"
            size="mini"
            @click="addDialog"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe v-if="!btnDisabled">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环显示属性标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="item"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row, 'confirm')"
                  @blur="handleInputConfirm(scope.row, 'cancel')"
                >
                </el-input>
                <!-- 切换输入文本框的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row"
                  type="success"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteattr(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="btnDisabled"
            type="primary"
            size="mini"
            @click="addDialog"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe v-if="!btnDisabled">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环显示属性标签 -->
                <el-tag
                  v-for="item in scope.row.attr_vals"
                  :key="item"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row, 'confirm')"
                  @blur="handleInputConfirm(scope.row, 'cancel')"
                >
                </el-input>
                <!-- 切换输入文本框的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row"
                  type="success"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteattr(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框区域 -->
    <el-dialog :title="titleText" :visible.sync="adddialogVisible" width="50%">
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addruleForm"
        label-width="100px"
      >
        <el-form-item label="添加数据" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="编辑数据" :visible.sync="editdialogVisible" width="50%">
      <el-form
        :model="editForm"
        :rules="editrules"
        ref="editruleForm"
        label-width="100px"
      >
        <el-form-item label="修改数据" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      catalist: [],
      selectedKeys: [],

      // 激活的tab
      activeName: 'many',

      // 动静态数据展示表格
      manyTableData: [],
      onlyTableData: [],

      adddialogVisible: false,
      editdialogVisible: false,
      inputVisible: false,

      // 添加数据对话框表单数据
      addForm: {
        attr_name: ''
      },
      addrules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },

      // 编辑对话框表单数据
      editForm: {
        attr_name: '',
        attr_sel: '',
        attr_id: ''
      },
      editrules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },

      // 属性id
      attrid: '',

      // 文本框输入的内容绑定值
      inputValue: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.catalist = res.data
    },

    // 级联变化会触发
    parentCateChanged () {
      if (this.selectedKeys.length === 0) {
        // this.manyTableData = this.onlyTableData = []
        return false
      }
      this.getParamsData()
    },

    // 单独抽离出来的获取数据的函数，级联选择器会调用，tab切换也应调用
    async getParamsData () {
      // 根据所选id和所处tab，获取对应参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制每个文本框的显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },

    // tab 点击事件
    handleTabClick () {
    },

    // 增加属性对话框事件
    addDialog () {
      this.adddialogVisible = true
    },

    // 提交增加属性
    addParams () {
      this.$refs.addruleForm.validate(async v => {
        if (v) {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 201) {
            return this.$message.error('提交失败')
          }
          this.$message.success('提交成功')
          this.adddialogVisible = false
          this.getParamsData()
        }
      })
    },

    // 编辑对话框
    showEditDialog (id) {
      this.attrid = id
      var obj = {}
      if (this.activeName === 'many') {
        obj = JSON.parse(JSON.stringify(this.manyTableData))
      } else {
        obj = JSON.parse(JSON.stringify(this.onlyTableData))
      }
      obj.some((na) => {
        if (na.attr_id === id) {
          this.editForm = na
          return true
        }
      })
      this.editdialogVisible = true
    },

    // 提交编辑对话框表单
    editParams () {
      this.$refs.editruleForm.validate(async v => {
        if (v) {
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.editForm.attr_sel
          })
          if (res.meta.status === 200) {
            this.$message.success('更新成功')
            this.editdialogVisible = false
            this.getParamsData()
          } else {
            this.$message.warning('更新失败')
          }
        }
      })
    },

    // 删除属性
    async deleteattr (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数，是否确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status === 200) {
        this.$message.success('删除成功')
      }
      this.getParamsData()
    },

    // 属性添加输入框
    handleInputConfirm (item, opt) {
      if (item.inputValue.trim().length === 0) {
        item.inputValue = ''
      } else {
        if (opt === 'confirm') {
          item.attr_vals.push(item.inputValue.trim())
          item.inputValue = ''
          this.editAttr(item)
        }
      }
      item.inputVisible = false
    },

    // 参数修改上传
    async editAttr (item) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`, {
        attr_name: item.attr_name,
        attr_sel: item.attr_sel,
        attr_vals: item.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改成功')
    },

    // 切换属性输入框
    showInput (item) {
      item.inputVisible = true
      // nextTick 的方法作用是 当页面上元素被重新渲染后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 删除属性标签
    handleClose (i, item) {
      item.attr_vals.splice(i, 1)
      this.editAttr(item)
    }
  },
  watch: {
    selectedKeys (n) {
      if (n.length !== 3 && n.length !== 0) {
        this.selectedKeys = []
        this.$message.warning('请选三级标题')
      }
    },

    // activeName变化会导致重新请求数据
    activeName () {
      if (this.selectedKeys.length !== 0) {
        this.getParamsData()
      }
    },

    adddialogVisible (n) {
      if (!n) {
        this.$refs.addruleForm.resetFields()
      }
    },

    editdialogVisible (n) {
      if (!n) {
        this.$refs.editruleForm.resetFields()
        this.editForm = {
          attr_name: '',
          attr_sel: '',
          attr_id: ''
        }
      }
      this.attrid = ''
    }
  },
  computed: {
    btnDisabled () {
      if (this.selectedKeys.length === 3) {
        return false
      }
      return true
    },

    // 动态计算对话框标题文本
    titleText () {
      if (this.activeName === 'many') {
        return '添加动态参数'
      }
      return '添加静态属性'
    },

    // 当前选中的三级分类id
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    }
  }
}
</script>

<style>
.cap_opt {
  margin-top: 15px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 120px !important;
}
</style>
